package com.dorm.cj.design.module;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;

import java.io.IOException;
import java.math.BigDecimal;

/*
BigDecimal反序列化时
 */
public class BigDecimalDeserializer extends StdScalarDeserializer<BigDecimal> {

    protected BigDecimalDeserializer() {
        super(BigDecimal.class);
    }

    @Override
    public BigDecimal deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonToken currentToken = jsonParser.getCurrentToken();
        if (currentToken == JsonToken.VALUE_STRING) {
            String bigDecimalStr = jsonParser.getText().trim();
            try {
                return new BigDecimal(bigDecimalStr);
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("bigDecimal parser exception");
            }
        }
        return (BigDecimal) deserializationContext.handleUnexpectedToken(BigDecimal.class, jsonParser);
    }
}
